#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Baka9'

import json
import random
import logging
import string
import requests
import urllib
import time
import os
import requests.packages.urllib3 as urllib3
urllib3.disable_warnings()

logging.getLogger("requests").setLevel(logging.WARNING)
logging.basicConfig(level=logging.INFO)

userName = ""
passWord = ""

PACKET_LOGIN = '{"cmdID":1,"verifyCode":"","isCompressed":0,"rsaKey":{"n":"D6F1CFBF4D9F70710527E1B1911635460B1FF9AB7C202294D04A6F135A906E90E2398123C234340A3CEA0E5EFDCB4BCF7C613A5A52B96F59871D8AB9D240ABD4481CCFD758EC3F2FDD54A1D4D56BFFD5C4A95810A8CA25E87FDC752EFA047DF4710C7D67CA025A2DC3EA59B09A9F2E3A41D4A7EFBB31C738B35FFAAA5C6F4E6F","e":"010001"},"businessType":61,"passWord":"%s","loginType":0,"platformVersion":1,"verifyKey":"","sessionID":"","protocolVersion":100,"userName":"%s","extensionList":"","sequenceNo":10000001,"peerID":"%s","clientVersion":"1.0.0"}'
PACKET_LOGIN2 = '{"cmdID":3,"userID":%s,"platformVersion":1,"sessionID":"%s","protocolVersion":100,"isCompressed":0,"businessType":61,"extensionList":["imgURL"],"sequenceNo":10000006,"peerID":"%s","clientVersion":"1.0.0"}'
s = requests.Session()
g_headers = {'User-Agent': 'android-async-http/1.4.3 (http://loopj.com/android-async-http)'}
g_headers2 = {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'}
g_cookies = {}
g_peerid = ''
g_userID = 0
g_totalnum = 0
g_totalbox = 0

n = '00D6F1CFBF4D9F70710527E1B1911635460B1FF9AB7C202294D04A6F135A906E90E2398123C234340A3CEA0E5EFDCB4BCF7C613A5A52B96F59871D8AB9D240ABD4481CCFD758EC3F2FDD54A1D4D56BFFD5C4A95810A8CA25E87FDC752EFA047DF4710C7D67CA025A2DC3EA59B09A9F2E3A41D4A7EFBB31C738B35FFAAA5C6F4E6F'
e = '010001'

import hashlib

def modpow(b, e, m):
    result = 1
    while (e > 0):
        if e & 1:
            result = (result * b) % m
        e = e >> 1
        b = (b * b) % m
    return result

def str_to_int(string):
    str_int = 0
    for i in range(len(string)):
        str_int = str_int << 8
        str_int += ord(string[i])
    return str_int

def rsa(data):
    result = modpow(str_to_int(data), long(e, 16), long(n, 16))
    return hex(result).upper()[2:-1]

def gen_passwd(passwd):
    return rsa(hashlib.md5(passwd).hexdigest())

def gen_peerID():
    return string.join(random.sample('ABCDEF0123456789', 16)).replace(' ', '')

g_peerid = gen_peerID()

# PC Browser Login Test


# userLogin,get cookies

def login():
    global g_headers
    global g_cookies
    global g_peerid
    data = PACKET_LOGIN % (gen_passwd(passWord), userName, g_peerid)
    r = requests.post('https://login.mobile.reg2t.sandai.net:443/', data, verify=False, headers=g_headers)
    if r.status_code != 200:
        raise Exception('Server Error...')
    ret = json.loads(r.text)
    if 'nickName' not in ret:
        logging.info('[登录失败]'.decode('utf-8'))
        raise Exception('login faild...')
    logging.info(('[登录成功:%s]' % ret['nickName'].encode('utf-8')).decode('utf-8'))
    g_userID = ret['userID']
    g_cookies['sessionid'] = ret['sessionID']
    g_cookies['userid'] = str(ret['userID']).encode('utf-8')
    g_cookies['origin'] = '1'

    data = PACKET_LOGIN2 % (g_cookies['userid'], g_cookies['sessionid'], g_peerid)
    r = requests.post('https://login.mobile.reg2t.sandai.net:443/', data, verify=False, headers=g_headers)

# getInfo
def post_info():
    r = requests.post('https://red.xunlei.com/index.php?r=usr/privilege', verify=False, headers=g_headers, cookies=g_cookies)
    if r.status_code != 200:
        raise Exception('Server Error...')
    ret = json.loads(r.text)
    mid = ret['mid']  # miners ID
    r = requests.post('https://red.xunlei.com/index.php?r=mine/info&v=2', verify=False, headers=g_headers, cookies=g_cookies)
    if r.status_code != 200:
        raise Exception('Server Error...')
    ret = json.loads(r.text)
    td_notcharged_num = ret['td_not_in_a']  # today not charged crystal
    td_pdc = ret['td_dev_pdc']  # today dev total output
    td_box_pdc = ret['td_box_pdc']  # today open box pdc
    td_boxop_num = ret['b_open']  # today open boxes num
    td_boxmiss_num = ret['b_open']  # today miss boxes num
    td_boxunop_num = ret['b_unget']  # today box unget
    td_crystmachine_pdc = ret['td_cm_pdc']  # today crystmachine pdc
    td_crystmachine_num = ret['cm_num']  # crystmachine num
    logging.info(('[今日矿场]:未收取%s,矿机产量%s,箱子出货量%s,雇佣产量%s' % (td_notcharged_num,td_pdc,td_box_pdc,td_crystmachine_pdc)).decode('utf-8'))


    r = requests.post('https://red.xunlei.com/index.php?r=mine/summary&v=3&f=1', verify=False, headers=g_headers, cookies=g_cookies)
    if r.status_code != 200:
        raise Exception('Server Error...')
    ret = json.loads(r.text)
    td_crystincome_num = ret['td_in_a']  # today cryst income
    logging.info(('[今日收入]:%s' % (td_crystincome_num)).decode('utf-8'))

    # machine info
    r = requests.post('https://red.xunlei.com/index.php?r=mine/devices_stat', verify=False, headers=g_headers, cookies=g_cookies)
    if r.status_code != 200:
        raise Exception('Server Error...')
    ret = json.loads(r.text)
    if ret['c'] == 2:  # if mechine num = 2
        # No.1 mechine
        mc_info1_name = ret['info'][0]['hn']  # No.1 mechine name
        mc_info1_speed = ret['info'][0]['s']  # No.1 mechine speed (kbps)
        mc_info1_type = ret['info'][0]['nm']  # No.1 mechine type
        mc_info1_ip = ret['info'][0]['ip']    # No.1 mechine ip address
        mc_info1_dvid = ret['info'][0]['dv_id']  # No.1 mechine device id
        logging.info(('[MC_INFO]:MCName%s,Speed%s' % (mc_info1_name,mc_info1_speed)).decode('utf-8'))

        # No.2 mechine
        mc_info2_name = ret['info'][1]['hn']  # No.2 mechine name
        mc_info2_speed = ret['info'][1]['s']  # No.2 mechine speed (kbps)
        mc_info2_type = ret['info'][1]['nm']  # No.2 mechine type
        mc_info2_ip = ret['info'][1]['ip']    # No.2 mechine ip address
        mc_info2_dvid = ret['info'][1]['dv_id']  # No.2 mechine device id
        logging.info(('[MC_INFO]:MCName%s,Speed%s' % (mc_info2_name,mc_info2_speed)).decode('utf-8'))





# CrystalCollect
def post_minecollect():
    data = 'v=2'
    r = requests.post('https://red.xunlei.com/index.php?r=mine/collect', data, verify=False, headers=g_headers, cookies=g_cookies)
    if r.status_code != 200:
        raise Exception('Server Error...')
    ret = json.loads(r.text)
    if ret['rd'] == 'ok':
        logging.info('[水晶收取成功]'.encode('utf-8')).decode('utf-8')




login()
post_info()
